package com.ruoyi.webs.utils.security;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class FrontLoginFilter
        implements Filter {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    private FilterConfig _filterConfig = null;

    private String excludedPages;

    private String[] excludedPageArray;
    private String frontPath;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this._filterConfig = filterConfig;
        this.excludedPages = filterConfig.getInitParameter("excludedPages");
        if (StringUtils.isNotEmpty(this.excludedPages)) {
            this.excludedPageArray = this.excludedPages.split(",");
        }
//        Properties loadFromFile = PropertiesUtil.loadFromFile("classpath://properties/jeeplus.properties");
//        String frontPath = PropertiesUtil.get(loadFromFile, "frontPath", "");
        this.frontPath = frontPath;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest rq = (HttpServletRequest) request;

        String contextPath = rq.getContextPath();
        String servletPath = rq.getServletPath();
        boolean isExcludedPage = false;
        byte b;
        int i;
        String[] arrayOfString;
        for (i = (arrayOfString = this.excludedPageArray).length, b = 0; b < i; ) {
            String page = arrayOfString[b];
            if (servletPath.equals(page.trim())) {
                isExcludedPage = true;
                break;
            }
            b++;
        }

        if (isExcludedPage) {
            chain.doFilter(request, response);
        } else {

            HttpSession httpSession = rq.getSession();
            String currentUnit = (String) httpSession.getAttribute("currentUnit");
            if (currentUnit == null) {

                HttpServletResponse rep = (HttpServletResponse) response;
                rep.sendRedirect(String.valueOf(contextPath) + this.frontPath + "/login");
            } else {
                chain.doFilter(request, response);
            }
        }
    }


}